import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { TouchableOpacity, ScrollView, View, Text, StyleSheet, Alert, ActivityIndicator } from 'react-native';
import { Icon, SearchBar, List, ListItem, FormInput, SideMenu, Button } from 'react-native-elements';
import Loader from './widgets/Loader';
import { toast, executor, primaryColor } from './utils';
import ModalDropdown from 'react-native-modal-dropdown';
import ClothesAutoInput from './components/ClothesAutoInput';
import { printOrder } from './printerUtils';
import { clearStorage } from './clientStorage';
import { NavigationActions } from 'react-navigation';

const styles = StyleSheet.create({
  header: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  itemRow: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 8,
  },
  input: {
    width: 120
  },
  fill: {
    flex: 1,
  },
  topText: {
    fontSize: 26,
    flex: 1,
    textAlign: 'center'
  },
  listTitle: {
    fontSize: 20,
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  bigFont: {
    fontSize: 20,
  },
  button: {
    fontSize: 20
  },
  buttonContainer: {
    marginVertical: 16
  },
  rejects: {
    backgroundColor: '#FFF59D',
    margin: 32
  },
  note: {
    fontSize: 20,
    color: primaryColor,
    padding: 16,
    backgroundColor: '#FBE9E7'
  }
});

class ItemCheckPage extends Component {
  static navigationOptions = ({screenProps, navigation}) => {
    return {
      title: screenProps.chinese?`衣物检查`:`Item Check`,
      tabBarIcon: ({tintColor}) => <Icon name='playlist-add-check' color={tintColor} size={24}/>
    };
  }
  state = { isOpen: false }
  onSearchChange=(value)=>{
    this.setState({value});
  }
  onSearch = () => {
    let value=this.state.value
    if ((value.slice(0,2).toLowerCase()==='kk'&&value.length>=6&&!isNaN(value.slice(2,6)))
      || (!isNaN(value)&&value.length>=5)) {
      if (this.isRequireUpdate(this.state)) {
        Alert.alert(
          `Brfore load new order, current order #${this.state.displayId} havn't updated after change items, do you want discard these changes? (Click the UPDATE & PRINT button to update an order after change items)`,
          `订单 #${this.state.displayId} 修改衣物后还没有更新，您是否要丢弃对改订单的修改？`,
          [
            {text: 'Cancel', onPress: () => this.setState({value: null})},
            {text: 'OK', onPress: () => this.searchOrder(value)},
          ],
          { cancelable: false }
        );
      } else {
        this.searchOrder(value);
      }
    }
  }
  searchOrder = (value) => {
    executor(this.props.loadOrder, value, null, true)
      .then(({res}) => {
        if (res) {
          if (res.loadOrder) {
            this.setState(this.updateOrderState(res.loadOrder));
          } else {
            Alert.alert(
              `Order not found by ${value}`,
              null,
              [
                {text: 'OK'},
              ],
              { cancelable: false }
            );
          }
        }
        this.setState({loading: false, value: null});
      });
    this.setState({loading: true});
  }
  updateOrderState = (order) => {
    const { pricing, ...others } = order||{};
    const originalDetails = pricing.details.filter(detail=>detail.productId);
    return {originalDetails, pricing, details: originalDetails, ...others};
  }
  isRequireUpdate = ({originalDetails, details}) => {
    if (!originalDetails||!details) return false;

    let reqeustUpdate;
    originalDetails.map(original => {
      if(!details.find(detail => detail.productId===original.productId && detail.quantity===original.quantity && detail.examptQuantity===original.examptQuantity && detail.quantityType===original.quantityType)) {
        reqeustUpdate = true;
      }
    });
    details.map(detail => {
      if(!originalDetails.find(original => detail.productId===original.productId && detail.quantity===original.quantity && detail.examptQuantity===original.examptQuantity && detail.quantityType===original.quantityType)) {
        reqeustUpdate = true;
      }
    });
    return reqeustUpdate;
  }
  onUpdateType = (index, type) => {
    console.log(index);
    console.log(type);
    const details = this.state.details;
    this.setState({details:[...details.slice(0,index), {...details[index], quantityType: type}, ...details.slice(index+1)]})
  }
  onAddQuantity = (index) => {
    const details = this.state.details;
    this.setState({details:[...details.slice(0,index), {...details[index], quantity: details[index].quantity+1}, ...details.slice(index+1)]})
  }
  onMiniusQuantity = (index) => {
    const details = this.state.details;
    const quantity = details[index].quantity-1;
    if (quantity > 0) {
      this.setState({details:[...details.slice(0,index), {...details[index], quantity}, ...details.slice(index+1)]});
    } else {
      this.setState({details:[...details.slice(0,index), ...details.slice(index+1)]});
    }
  }
  onAddExamptQuantity = (index) => {
    const details = this.state.details;
    this.setState({details:[...details.slice(0,index), {...details[index], examptQuantity: (details[index].examptQuantity||0)+1}, ...details.slice(index+1)]})
  }
  onMiniusExamptQuantity = (index) => {
    const details = this.state.details;
    const examptQuantity = (details[index].examptQuantity||0)-1;
    if (examptQuantity >= 0) {
      this.setState({details:[...details.slice(0,index), {...details[index], examptQuantity}, ...details.slice(index+1)]});
    }
  }
  onToggleMenu = () => this.setState({isOpen:!this.state.isOpen})
  onSideMenuChange = (isOpen) => this.setState({isOpen})
  onAddItem = ({productName, productId, quantity, quantityType, quantityTypeOptions}) => {
    const details = this.state.details;
    const index = details.findIndex(item => item.productId===productId&&item.quantityType===quantityType);
    this.setState({details: index<0?[...details, {productName, productId, quantity, quantityType, quantityTypeOptions}]
      :[...details.slice(0,index), {...details[index], quantity:quantity+details[index].quantity}, ...details.slice(index+1)]});
  }
  onPrint = () => {
    const { id, details } = this.state;
    if (!id) return toast('Please find an order first');

    const requireUpdate = this.isRequireUpdate(this.state);
    if (requireUpdate) {
      Alert.alert(
        `Customer will receive notification about this update, please make things right only by 1 update.`,
        null,
        [
          {text: this.props.chinese?'取消':'Cancel'},
          {text: this.props.chinese?'确定':'Update & Print', onPress: () => this.onSubmit(id, details, requireUpdate)},
        ],
        { cancelable: true }
      );
    } else {
      this.onSubmit(id, details, requireUpdate);
    }
  }
  onSubmit = (id, details, requireUpdate) => {
    Promise.resolve(requireUpdate&&executor(this.props.updateOrderV2, {
        orderId: id,
        orderItems: details.map(({productId,quantity,examptQuantity,quantityType})=>({id:productId,count:quantity,examptCount:examptQuantity,type:quantityType}))
      }))
      .then((response) => {
        const newState = response&&response.res&&this.updateOrderState(response.res.updateOrderV2[0]);
        if (newState) {
          this.setState(newState);
        }
        return printOrder({...(newState||this.state)}, this.props.worker);
      })
      .then(() => this.setState({printing: false}))
      .catch(() => this.setState({printing: false}))
    this.setState({printing: true});
  }
  onContact = () => {
    this.props.navigation.navigate('ContactCustomer',
      {displayId: this.state.displayId, orderId: this.state.id, userId: this.state.userId});
  }
  onReject = () => {
    console.log(this.state.details);
    this.props.navigation.navigate('RejectItems',
      {details: this.state.details, orderId: this.state.id, displayId: this.state.displayId,
        onSuccess: () => this.searchOrder(this.state.displayId)});
  }
  onTakePhotos = () => {
    this.props.navigation.navigate('PhotoUpload',
      {displayId: this.state.displayId, orderId: this.state.id, userId: this.state.userId});
  }
  render() {
    if (!this.props.worker||this.props.loading) return <Loader/>;
    const { loading, displayId, estDate, details, userId, userRef, type, cloth,
      quantity, quantityType, printing } = this.state;
    const dryCount = details&&[0, ...details.filter(item => item.quantityType==='dry').map(item=>item.quantity)].reduce((a,b)=>a+b);
    const washCount = details&&[0, ...details.filter(item => item.quantityType!=='dry').map(item=>item.quantity)].reduce((a,b)=>a+b);
    const chinese = this.props.screenProps.chinese;

    return (
      <SideMenu isOpen={this.state.isOpen} onChange={this.onSideMenuChange}
        menu={<ClothesAutoInput chinese={false} userId={userId} type={type} onAddItem={this.onAddItem}/>}>
        <View style={{flex: 1, backgroundColor: 'white'}}>
          <View style={styles.header}>
            <View style={styles.fill}>
              <SearchBar inputStyle={{height:50}} autoFocus lightTheme onChangeText={this.onSearchChange} placeholder='Bag/Order num'
                value={this.state.value}/>
            </View>
            <View style={[{alignItems:'center'}]}>
                <Button textStyle={styles.button} title={chinese?'搜索':'Search'} backgroundColor={primaryColor} onPress={this.onSearch}/>
            </View>
          </View>
          <View style={styles.header}>
            <View style={styles.fill}>
              {displayId&&<Button textStyle={styles.button} title={chinese?'添加':'Add'} backgroundColor={primaryColor}
                onPress={this.onToggleMenu}/>}
            </View>
            <View style={[styles.fill, {alignItems:'center'}]}>
              {printing?<ActivityIndicator/>:
                <Button textStyle={styles.button} title={this.isRequireUpdate(this.state)?(chinese?`更新&打印`:`Update & Print`):(chinese?'打印':'Print')} backgroundColor={primaryColor} onPress={this.onPrint}/>
              }
            </View>
          </View>
          {loading?<ActivityIndicator style={{padding: 40}}/>:
            <ScrollView>
              {displayId&&
                <View style={[styles.header, {paddingTop: 12}]}>
                  <Text style={styles.topText}>
                    k2
                  </Text>
                  <Text style={styles.topText}>
                    {displayId}
                  </Text>
                  <Text style={styles.topText}>
                    {`${washCount?`W-${washCount}`:''}${(washCount&&dryCount)?' / ':''}${dryCount?`D-${dryCount}`:''}`}
                  </Text>
                  <Text style={styles.topText}>
                    {estDate}
                  </Text>
                </View>
              }
              {userRef?<Text style={styles.note}>{`[${userRef.firstName}] ${userRef.internalTags?`${chinese?'请注意':'Note'}: ${userRef.internalTags}`:''}`}</Text>:null}
              {details&&details.map((detail, index) =>
                  <View key={index} style={styles.itemRow}>
                    <View style={styles.listTitle}>
                      <Text style={styles.listTitle}>{detail.productName}</Text>
                    </View>
                    <View style={{flex:1, alignItems: 'center'}}>
                      <ModalDropdown textStyle={{fontSize:22}} dropdownTextStyle={{fontSize:22}}
                        defaultValue={detail.quantityType} onSelect={(a,type)=>this.onUpdateType(index,type)}
                        options={detail.quantityTypeOptions}/>
                    </View>
                    <View style={{flex:1, alignItems:'center', flexDirection:'row', justifyContent:'center'}}>
                      <Icon name='add' color='green' size={40} onPress={()=>this.onAddQuantity(index)}/>
                      <Text style={{fontSize:20,paddingHorizontal:8}}>{detail.quantity}</Text>
                      <Icon name='remove' color='red' size={40} onPress={()=>this.onMiniusQuantity(index)}/>
                    </View>
                  </View>
                )
              }
              {userId&&
                <View style={styles.rejects}>
                  <Text style={{fontSize:24, margin: 16}}>{chinese?'退回衣物':'Reject Items'}</Text>
                  {details&&details.map((detail, index) =>
                      <View key={index} style={styles.itemRow}>
                        <View style={styles.listTitle}>
                          <Text style={styles.listTitle}>{detail.productName}</Text>
                        </View>
                        <View style={{flex:1, alignItems: 'center'}}>
                          <Text style={styles.listTitle}>{detail.quantityType}</Text>
                        </View>
                        <View style={{flex:1, alignItems:'center', flexDirection:'row', justifyContent:'center'}}>
                          <Icon name='add' color='green' size={40} onPress={()=>this.onAddExamptQuantity(index)}/>
                          <Text style={{fontSize:20,paddingHorizontal:8}}>{detail.examptQuantity||0}</Text>
                          <Icon name='remove' color='red' size={40} onPress={()=>this.onMiniusExamptQuantity(index)}/>
                        </View>
                      </View>
                    )
                  }
                </View>
              }
              {userId&&
                <Button title={chinese?'订单反馈':'Order Feedback'} containerViewStyle={{marginVertical:16}} onPress={this.onContact}/>
              }
              {userId&&
                <Button title={chinese?'拍照':'Take Photos'} containerViewStyle={{marginVertical:16}} onPress={this.onTakePhotos}/>
              }
            </ScrollView>
          }
        </View>
      </SideMenu>
    );
  }
}

export default compose(
  graphql(gql`
    query ItemCheckPage {
      worker {
        id
        firstName
        lastName
      }
    }
  `, {
    props: ({data:{worker, loading}}) => {
      return {
        worker,
        loading
      };
    }
  }),
  graphql(gql`
    mutation loadOrder($idOrBag:String!) {
      loadOrder(idOrBag:$idOrBag) {
        id
        type
        estDate
        userId
        estDate
        displayId
        printBrand
        warningNotes
        pickup {
          date
        }
        userRef {
          firstName
          internalTags
        }
        delivery {
          district
          postalCode
          express
        }
        pricing {
          details(chinese:false) {
            price
            description
            productName
            productId
            quantity
            examptQuantity
            quantityType
            imageUrl
            quantityTypeOptions
            price
            special
          }
        }
      }
    }
  `, {
    name: 'loadOrder',
    props: ({loadOrder}) => {
      return {
        loadOrder: (idOrBag) => loadOrder({variables:{idOrBag}})
      }
    }
  }),
  graphql(gql`
    mutation updateOrderV2($orderId:String!,$orderItems:[OrderItemInput]) {
      updateOrderV2(orderId:$orderId,orderItems:$orderItems){
        id
        type
        estDate
        userId
        estDate
        displayId
        printBrand
        warningNotes
        pickup {
          date
        }
        userRef {
          firstName
          internalTags
        }
        delivery {
          district
          postalCode
          express
        }
        pricing {
          details(chinese:false) {
            price
            description
            productName
            productId
            quantity
            examptQuantity
            quantityType
            imageUrl
            quantityTypeOptions
            price
            special
          }
        }
      }
    }
  `, {
    name: 'updateOrderV2',
    props: ({updateOrderV2}) => {
      return {
        updateOrderV2: (variables) => updateOrderV2({variables})
      }
    }
  }),
)(ItemCheckPage);

